"""
PUA语言检测服务
"""
import re
import json
from typing import Dict, List, Any, Optional
import logging

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.pua import PUAPattern, PUAPatternCategory
from app.db.session import get_db

logger = logging.getLogger(__name__)

class PUADetector:
    """PUA语言检测器"""

    def __init__(self):
        """初始化PUA检测器"""
        self.patterns = []  # 缓存已加载的模式
        self.patterns_loaded = False
    
    async def load_patterns(self, db: AsyncSession) -> None:
        """从数据库加载PUA模式"""
        try:
            # 查询所有PUA模式
            result = await db.execute(select(PUAPattern))
            patterns = result.scalars().all()
            
            self.patterns = []
            for pattern in patterns:
                compiled_pattern = re.compile(pattern.pattern)
                self.patterns.append({
                    "id": pattern.id,
                    "pattern": compiled_pattern,
                    "raw_pattern": pattern.pattern,
                    "category": pattern.category,
                    "description": pattern.description,
                    "severity": pattern.severity,
                    "examples": json.loads(pattern.examples) if pattern.examples else [],
                    "response_templates": json.loads(pattern.response_templates) if pattern.response_templates else []
                })
            
            self.patterns_loaded = True
            logger.info(f"成功加载 {len(self.patterns)} 个PUA模式")
        except Exception as e:
            logger.error(f"加载PUA模式失败: {str(e)}")
            self.patterns_loaded = False
    
    async def detect_pua(self, text: str) -> Dict[str, Any]:
        """
        检测文本中的PUA语言
        
        Args:
            text: 待检测的文本
            
        Returns:
            Dict[str, Any]: 检测结果
        """
        # 获取数据库连接
        async for db in get_db():
            # 如果模式未加载，则加载模式
            if not self.patterns_loaded:
                await self.load_patterns(db)
            
            # 如果模式仍未加载，返回空结果
            if not self.patterns_loaded:
                return {
                    "is_pua": False,
                    "score": 0.0,
                    "detected_patterns": [],
                    "message": "无法加载PUA模式"
                }
            
            # 检测匹配的模式
            detected = []
            max_severity = 0.0
            
            for pattern in self.patterns:
                if pattern["pattern"].search(text):
                    detected.append({
                        "id": pattern["id"],
                        "category": pattern["category"],
                        "description": pattern["description"],
                        "severity": pattern["severity"],
                        "matched_pattern": pattern["raw_pattern"],
                        "response_templates": pattern["response_templates"] if "response_templates" in pattern else []
                    })
                    
                    max_severity = max(max_severity, pattern["severity"])
            
            # 根据检测结果生成分数
            is_pua = len(detected) > 0
            score = max_severity
            
            return {
                "is_pua": is_pua,
                "score": score,
                "detected_patterns": detected,
                "message": "检测到PUA语言" if is_pua else "未检测到PUA语言"
            }
        
        # 如果无法获取数据库连接，返回空结果
        return {
            "is_pua": False,
            "score": 0.0,
            "detected_patterns": [],
            "message": "无法连接数据库"
        }


# 创建全局PUA检测器实例
pua_detector = PUADetector() 